<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { getClassListByUserIdService, getUserListByClassIdListService } from '@/api/user_classname'
import { useUserStore } from '@/stores'
import { TStudentScore, TScoreRadio, ExamStatus } from '@/Types/education.d'
import { getSubjectListService } from '@/api/education/subject'
import { getScoreRadioListServer } from '@/api/education/scoreRadio'
import { Upload, Edit, Check } from '@element-plus/icons-vue'
import { addScoreListService, getScoreListBySpecificService } from '@/api/education/score'

/**
 * 初始化
 */
// 科目类型（普通科目、特殊科目  普通包含期中、期末、平时 —— 特殊包含期末、平时）
type SubjectType = 'normal' | 'special'
// 表单数据
const filterForm = ref({
	academicYear: '',
	classname: '',
	subject: '',
	subjectType: 'normal' as SubjectType,
	radioId: undefined as number | undefined
})
// 下拉选项数据
const academicYears = ref([
	{ value: '2023-2024', label: '2023-2024' },
	{ value: '2022-2023', label: '2022-2023' }
])
const classes = ref([
	{ value: 'class1', label: '一班' },
	{ value: 'class2', label: '二班' }
])
const subjects = ref([
	{ value: 'chinese', label: '语文', type: 'normal' },
	{ value: 'math', label: '数学', type: 'normal' },
	{ value: 'pe', label: '体育', type: 'special' }
])
// 学生数据
const students = ref<TStudentScore[]>([])
const loading = ref(false)
const formRef = ref<FormInstance>()
const isEditing = ref(false)

// 成绩比例选项
const scoreRadioOptions = ref<TScoreRadio[]>([])
const selectedRadio = ref<TScoreRadio>()
const radioDisabled = ref(false)

// 考试情况选项
const examStatusOptions = [
	{ value: 'normal', label: '正常' },
	{ value: 'absent', label: '缺考' },
	{ value: 'violation', label: '作弊' }
]

// 添加用于跟踪无效分数输入的变量
const invalidScores = ref<Record<string, boolean>>({})

/**
 * 数据处理
 */
// 计算公式
const calculateScore = (score: number | undefined, radio: number) => (score ?? 0) * radio // score ?? 0  当score为undefined时，赋为0
// 计算总分
const calculateTotal = (scores: TStudentScore['scores'], type: string) => {
	if (!selectedRadio.value) return '0'

	// 如果已经有总分，直接返回总分
	if (type === 'theory' && scores.theoryTotal !== undefined) {
		return scores.theoryTotal.toFixed(1)
	}
	if (type === 'practice' && scores.practiceTotal !== undefined) {
		return scores.practiceTotal.toFixed(1)
	}

	const radio = selectedRadio.value
	if (type === 'theory') {
		if (radio.type === 'normal') {
			return (
				calculateScore(scores.midTermTheory, radio.midTerm) +
				calculateScore(scores.finalTheory, radio.finalTerm) +
				calculateScore(scores.usualTheory, radio.usual)
			).toFixed(1)
		} else {
			// 特殊科目只有期末和平时
			return (
				calculateScore(scores.finalTheory, radio.finalTerm) +
				calculateScore(scores.usualTheory, radio.usual)
			).toFixed(1)
		}
	} else {
		if (radio.type === 'normal') {
			return (
				calculateScore(scores.midTermPractice, radio.midTerm) +
				calculateScore(scores.finalPractice, radio.finalTerm) +
				calculateScore(scores.usualPractice, radio.usual)
			).toFixed(1)
		} else {
			// 特殊科目只有期末和平时
			return (
				calculateScore(scores.finalPractice, radio.finalTerm) +
				calculateScore(scores.usualPractice, radio.usual)
			).toFixed(1)
		}
	}
}
// 更新分数
const updateScore = (row: TStudentScore, field: keyof TStudentScore['scores'], value: string) => {
	// 如果是考试情况字段，直接更新
	if (field === 'aboutTheory' || field === 'aboutPractice') {
		row.scores[field] = value as ExamStatus
		return true
	}

	// 如果是分数字段
	const score = Number(value)
	// 生成唯一键值，用于标识哪些分数是无效的
	const invalidKey = `${row.userId}_${field}`

	if (isNaN(score) || score < 0 || score > 100) {
		ElMessage.error('请输入0-100之间的有效分数')
		// 标记无效
		invalidScores.value[invalidKey] = true

		// 恢复为上一个有效值或者空值
		// 如果当前值不是数字，我们设置为undefined以避免显示NaN
		if (isNaN(score)) {
			row.scores[field] = undefined
		}
		return false
	}

	// 有效分数，移除无效标记
	if (invalidScores.value[invalidKey]) {
		delete invalidScores.value[invalidKey]
	}

	row.scores[field] = score
	return true
}
// // 处理科目变更
// const handleSubjectChange = (value: string) => {
// 	const subject = subjects.value.find((s) => s.value === value)
// }

/**
 * 数据获取
 */
// 获取班级列表
const getClassList = async () => {
	const userStore = useUserStore()
	const res = await getClassListByUserIdService(userStore.userInfo.userInfo.userId)

	// 格式化班级数据
	classes.value = res.data.data.map((item: any) => {
		const levelMap = {
			vocEd: '专科',
			undergrad: '本科'
		}
		const level = levelMap[item.level as keyof typeof levelMap] || '未知'

		return {
			value: item.classId,
			// 格式：本科-软件学院-软件工程技术-2020级-101班
			label: `${level}-${item.academy}-${item.major}-${item.grade}级-${item.classname}班`,
			// 保存原始数据，以备后用
			raw: item
		}
	})
}
// 获取科目列表
const getSubjectList = async () => {
	const res = await getSubjectListService()
	if (res.data.code === 1) {
		subjects.value = res.data.data.map((item: any) => ({
			value: item.id,
			label: item.subject
		}))
	} else {
		ElMessage.error(res.data.msg)
	}
}
// 格式化比例显示
const formatRadioLabel = (radio: TScoreRadio) => {
	if (radio.type === 'normal') {
		return `期中(${radio.midTerm * 100}%)、期末(${radio.finalTerm * 100}%)、平时(${radio.usual * 100}%)`
	} else {
		return `期末(${radio.finalTerm * 100}%)、平时(${radio.usual * 100}%)`
	}
}
// 获取成绩比例列表
const getScoreRadioList = async () => {
	const res = await getScoreRadioListServer()
	if (res.data.code === 1) {
		scoreRadioOptions.value = res.data.data.map((radio: any) => ({
			...radio,
			// 添加显示用的label属性
			label: formatRadioLabel(radio)
		}))
		// console.log(scoreRadioOptions.value)
	} else {
		ElMessage.error(res.data.msg)
	}
}
// 获取学生列表
const getStudentList = async () => {
	// 表单验证
	if (!filterForm.value.classname || !filterForm.value.academicYear || !filterForm.value.subject) {
		ElMessage.warning('请填写完整查询条件')
		return
	}

	loading.value = true
	// 重置比例选择状态
	filterForm.value.radioId = undefined
	radioDisabled.value = false

	try {
		// 获取该班级的学生
		const classIdList = [Number(filterForm.value.classname)]
		const res = await getUserListByClassIdListService(1, classIdList)

		// 转换数据结构
		students.value = res.data.data.map((student: any) => ({
			userId: student.userId,
			studentId: student.typeNumber,
			name: student.uname,
			scores: {
				midTermTheory: undefined,
				finalTheory: undefined,
				usualTheory: undefined,
				midTermPractice: undefined,
				finalPractice: undefined,
				usualPractice: undefined,
				aboutTheory: 'normal',
				aboutPractice: 'normal'
			}
		}))

		// 获取用户对应的成绩
		const scoreRes = await getScoreListBySpecificService({
			// studentId: students.value.map((s) => s.userId),
			academicYear: filterForm.value.academicYear,
			classId: filterForm.value.classname,
			subjectId: filterForm.value.subject
		})

		console.log(scoreRes.data.data)
		if (scoreRes.data.code === 1 && scoreRes.data.data.length > 0) {
			// 成绩存在
			// 禁用比例
			radioDisabled.value = true
			// 获取当前比例
			const currentRadio = scoreRes.data.data[0].radioId
			// 将当前比例赋值给filterForm.value.radioId
			filterForm.value.radioId = currentRadio

			// 设置科目类型
			const selectedRadioOption = scoreRadioOptions.value.find((r) => r.id === currentRadio)
			if (selectedRadioOption) {
				filterForm.value.subjectType = selectedRadioOption.type
				selectedRadio.value = selectedRadioOption
			}

			// 将数据库中的成绩赋值给学生
			students.value.forEach((student) => {
				const score = scoreRes.data.data.find((s: any) => s.studentId === student.userId)
				if (score) {
					student.scores = {
						midTermTheory: score.midTermTheory || undefined,
						finalTheory: score.finalTheory || undefined,
						usualTheory: score.usualTheory || undefined,
						theoryTotal: score.theoryTotal || undefined,
						midTermPractice: score.midTermPractice || undefined,
						finalPractice: score.finalPractice || undefined,
						usualPractice: score.usualPractice || undefined,
						practiceTotal: score.practiceTotal || undefined,
						aboutTheory: score.aboutTheory || 'normal',
						aboutPractice: score.aboutPractice || 'normal'
					}
				}
			})
		}
	} catch (error) {
		console.error('获取数据失败:', error)
		ElMessage.error('获取数据失败')
	} finally {
		loading.value = false
	}
}

// 监听比例变化
const handleRadioChange = (value: number) => {
	if (!value) return

	const selectedRadioOption = scoreRadioOptions.value.find((r) => r.id === value)
	if (selectedRadioOption) {
		filterForm.value.subjectType = selectedRadioOption.type
		selectedRadio.value = selectedRadioOption
	}
}

// 添加检查分数是否有填写的辅助函数
const hasAnyTheoryScore = (scores: TStudentScore['scores']) => {
	return (
		scores.midTermTheory !== undefined ||
		scores.finalTheory !== undefined ||
		scores.usualTheory !== undefined
	)
}

const hasAnyPracticeScore = (scores: TStudentScore['scores']) => {
	return (
		scores.midTermPractice !== undefined ||
		scores.finalPractice !== undefined ||
		scores.usualPractice !== undefined
	)
}

// 检查缺考或作弊情况下的分数是否符合要求（至少有一个分数为0）
const isAbsentOrViolationValid = (scores: TStudentScore['scores'], type: 'theory' | 'practice') => {
	if (type === 'theory') {
		// 对于缺考或作弊情况，至少有一个成绩为0
		return scores.midTermTheory === 0 || scores.finalTheory === 0 || scores.usualTheory === 0
	} else {
		// 对于缺考或作弊情况，至少有一个成绩为0
		return scores.midTermPractice === 0 || scores.finalPractice === 0 || scores.usualPractice === 0
	}
}

// 由于期中、期末、平时可以分开录入，我们不再检查完整性，而是检查已填写的分数是否有效
const isScoreValid = (score: number | undefined) => {
	return score === undefined || (score >= 0 && score <= 100)
}

// 添加编辑和保存的处理函数
const handleEdit = () => {
	// 验证是否已选择比例
	if (!filterForm.value.radioId) {
		ElMessage.warning('请先选择成绩比例')
		return
	}
	isEditing.value = true
}

const handleSave = () => {
	// 检查是否存在无效分数
	const hasInvalidScore = Object.keys(invalidScores.value).length > 0
	if (hasInvalidScore) {
		ElMessage.warning('请修正红色标记的分数')
		return
	}

	// 检查所有学生的分数有效性
	const invalidStudents: string[] = []
	const absentViolationInvalidStudents: string[] = []

	students.value.forEach((student) => {
		const { scores, name } = student
		let hasInvalidScore = false
		let hasAbsentViolationInvalid = false

		// 验证理论部分
		// 先验证考试情况为缺考或作弊时的分数
		if (scores.aboutTheory !== 'normal') {
			if (!isAbsentOrViolationValid(scores, 'theory')) {
				hasAbsentViolationInvalid = true
			}
		} else {
			// 正常情况，验证已填写的分数是否有效
			if (
				!isScoreValid(scores.midTermTheory) ||
				!isScoreValid(scores.finalTheory) ||
				!isScoreValid(scores.usualTheory)
			) {
				hasInvalidScore = true
			}
		}

		// 验证实践部分
		// 先验证考试情况为缺考或作弊时的分数
		if (scores.aboutPractice !== 'normal') {
			if (!isAbsentOrViolationValid(scores, 'practice')) {
				hasAbsentViolationInvalid = true
			}
		} else {
			// 正常情况，验证已填写的分数是否有效
			if (
				!isScoreValid(scores.midTermPractice) ||
				!isScoreValid(scores.finalPractice) ||
				!isScoreValid(scores.usualPractice)
			) {
				hasInvalidScore = true
			}
		}

		if (hasInvalidScore) {
			invalidStudents.push(name)
		}

		if (hasAbsentViolationInvalid) {
			absentViolationInvalidStudents.push(name)
		}
	})

	if (absentViolationInvalidStudents.length > 0) {
		if (absentViolationInvalidStudents.length <= 3) {
			ElMessage.warning(
				`学生${absentViolationInvalidStudents.join('、')}缺考或作弊，分数不合规，请修正`
			)
		} else {
			ElMessage.warning(
				`${absentViolationInvalidStudents.length}名学生缺考或作弊，分数不合规，请修正`
			)
		}
		return
	}

	if (invalidStudents.length > 0) {
		if (invalidStudents.length <= 3) {
			ElMessage.warning(`学生 ${invalidStudents.join('、')} 的成绩有误，请检查后再保存`)
		} else {
			ElMessage.warning(`${invalidStudents.length}名学生成绩有误，请检查后再保存`)
		}
		return
	}

	isEditing.value = false
	ElMessage.success('保存成功')
}

/**
 * 成绩上传
 */
const uploadScore = async () => {
	if (!filterForm.value.classname || !filterForm.value.academicYear || !filterForm.value.subject) {
		ElMessage.warning('请先完善表单信息')
		return
	}

	// 检查是否选择了比例
	if (!filterForm.value.radioId) {
		ElMessage.warning('请先选择成绩比例')
		return
	}

	// 检查是否有学生数据
	if (!students.value.length) {
		ElMessage.warning('暂无学生数据')
		return
	}

	// 验证所有分数的合规性
	const invalidStudents: string[] = []
	const absentViolationInvalidStudents: string[] = []

	students.value.forEach((student) => {
		const { scores, name } = student
		let hasInvalidScore = false
		let hasAbsentViolationInvalid = false

		// 验证理论部分
		// 先验证考试情况为缺考或作弊时的分数
		if (scores.aboutTheory !== 'normal') {
			if (!isAbsentOrViolationValid(scores, 'theory')) {
				hasAbsentViolationInvalid = true
			}
		} else {
			// 正常情况，验证已填写的分数是否有效
			if (
				!isScoreValid(scores.midTermTheory) ||
				!isScoreValid(scores.finalTheory) ||
				!isScoreValid(scores.usualTheory)
			) {
				hasInvalidScore = true
			}
		}

		// 验证实践部分
		// 先验证考试情况为缺考或作弊时的分数
		if (scores.aboutPractice !== 'normal') {
			if (!isAbsentOrViolationValid(scores, 'practice')) {
				hasAbsentViolationInvalid = true
			}
		} else {
			// 正常情况，验证已填写的分数是否有效
			if (
				!isScoreValid(scores.midTermPractice) ||
				!isScoreValid(scores.finalPractice) ||
				!isScoreValid(scores.usualPractice)
			) {
				hasInvalidScore = true
			}
		}

		if (hasInvalidScore) {
			invalidStudents.push(name)
		}

		if (hasAbsentViolationInvalid) {
			absentViolationInvalidStudents.push(name)
		}
	})

	// 先检查缺考或作弊的情况
	if (absentViolationInvalidStudents.length > 0) {
		if (absentViolationInvalidStudents.length <= 3) {
			ElMessage.warning(
				`学生 ${absentViolationInvalidStudents.join('、')} 设置了缺考或作弊，但分数不为0，请修正`
			)
		} else {
			ElMessage.warning(
				`${absentViolationInvalidStudents.length}名学生设置了缺考或作弊，但分数不为0，请修正`
			)
		}
		return
	}

	// 如果有无效分数，停止上传并提示
	if (invalidStudents.length > 0) {
		if (invalidStudents.length <= 3) {
			ElMessage.warning(`学生 ${invalidStudents.join('、')} 的成绩有误，请检查后再上传`)
		} else {
			ElMessage.warning(`${invalidStudents.length}名学生成绩有误，请检查后再上传`)
		}
		return
	}

	// 构造成绩数据
	const scoreList = students.value.map((student) => {
		const { scores } = student
		const userStore = useUserStore()
		return {
			classId: Number(filterForm.value.classname),
			studentId: student.userId, // 用户id
			subjectId: Number(filterForm.value.subject),
			radioId: filterForm.value.radioId,
			judgeId: userStore.userInfo.userInfo.userId,
			academicYear: filterForm.value.academicYear,
			// 理论成绩
			midTermTheory: scores.midTermTheory,
			finalTheory: scores.finalTheory,
			usualTheory: scores.usualTheory,
			aboutTheory: scores.aboutTheory,
			// 实践成绩
			midTermPractice: scores.midTermPractice,
			finalPractice: scores.finalPractice,
			usualPractice: scores.usualPractice,
			aboutPractice: scores.aboutPractice,
			// 总分
			theoryTotal: Number(calculateTotal(scores, 'theory')),
			practiceTotal: Number(calculateTotal(scores, 'practice'))
		}
	})

	try {
		const res = await addScoreListService(scoreList)
		if (res.data.code === 1) {
			ElMessage.success('成绩上传成功')
			// 上传成功后禁用比例选择
			radioDisabled.value = true
		} else {
			ElMessage.error(res.data.msg || '成绩上传失败')
		}
	} catch (error) {
		console.error('成绩上传失败:', error)
		ElMessage.error('成绩上传失败')
	}
}

/**
 * 生命周期
 */
onMounted(() => {
	getClassList()
	getSubjectList()
	getScoreRadioList()
})
</script>

<template>
	<div class="score-input">
		<el-card class="filter-card">
			<el-form ref="formRef" :model="filterForm" class="filter-form">
				<div class="form-row">
					<el-form-item label="班级" prop="classname" required>
						<el-select v-model="filterForm.classname" placeholder="选择">
							<el-option
								v-for="item in classes"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="学年" prop="academicYear" required class="small-item">
						<el-select v-model="filterForm.academicYear" placeholder="选择">
							<el-option
								v-for="item in academicYears"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="科目" prop="subject" required class="small-item">
						<el-select v-model="filterForm.subject" placeholder="选择">
							<el-option
								v-for="item in subjects"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>

					<el-form-item>
						<el-button type="primary" @click="getStudentList">查询</el-button>
					</el-form-item>

					<el-form-item
						label="比例"
						prop="radioId"
						style="position: absolute; right: 20px; width: 320px"
					>
						<el-select v-model="filterForm.radioId" placeholder="选择" @change="handleRadioChange">
							<el-option
								v-for="item in scoreRadioOptions"
								:key="item.id"
								:label="item.label"
								:value="item.id"
								:disabled="radioDisabled"
							/>
						</el-select>
					</el-form-item>
				</div>
			</el-form>
		</el-card>

		<el-card class="table-card">
			<template #header>
				<div class="table-header">
					<div class="title-section">
						<h1>成绩录入</h1>
						<div class="selected-info">
							<span
								>班级:
								{{ classes.find((c) => c.value === filterForm.classname)?.label || '-' }}</span
							>
							<span
								>学年:
								{{
									academicYears.find((y) => y.value === filterForm.academicYear)?.label || '-'
								}}</span
							>
							<span
								>科目:
								{{ subjects.find((s) => s.value === filterForm.subject)?.label || '-' }}</span
							>
							<span
								>比例:
								{{ scoreRadioOptions.find((r) => r.id === filterForm.radioId)?.label || '-' }}</span
							>
						</div>
					</div>
					<div class="button-group">
						<el-button
							:type="isEditing ? 'primary' : 'warning'"
							:icon="isEditing ? Check : Edit"
							@click="isEditing ? handleSave() : handleEdit()"
							:disabled="!filterForm.radioId || !students.length"
						>
							{{ isEditing ? '保存' : '录入' }}
						</el-button>
						<el-button
							type="primary"
							:icon="Upload"
							@click="uploadScore"
							:disabled="!filterForm.radioId || !students.length || isEditing"
						>
							上传
						</el-button>
					</div>
				</div>
			</template>

			<el-table :data="students" border v-loading="loading" class="score-table">
				<el-table-column type="index" label="序号" width="50" align="center" />
				<el-table-column prop="name" label="姓名" width="80" align="center" />
				<el-table-column prop="studentId" label="学号" width="110" align="center" sortable />

				<!-- 理论成绩部分 -->
				<el-table-column label="理论成绩" align="center">
					<!-- 考试情况选择 -->
					<el-table-column label="考试情况" width="100" align="center">
						<template #default="{ row }">
							<el-select
								v-if="isEditing"
								v-model="row.scores.aboutTheory"
								placeholder="选择"
								@change="(value: string) => updateScore(row, 'aboutTheory', value)"
							>
								<el-option
									v-for="item in examStatusOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</el-select>
							<span v-else>{{
								examStatusOptions.find((o) => o.value === row.scores.aboutTheory)?.label
							}}</span>
						</template>
					</el-table-column>

					<!-- 期中列 - 只在普通科目时显示 -->
					<el-table-column
						v-if="filterForm.subjectType === 'normal'"
						label="期中"
						width="85"
						align="center"
					>
						<template #default="{ row }">
							<el-input
								v-if="isEditing"
								v-model="row.scores.midTermTheory"
								@change="(value: string) => updateScore(row, 'midTermTheory', value)"
								:class="{ 'invalid-input': invalidScores[`${row.userId}_midTermTheory`] }"
							/>
							<span v-else>{{ row.scores.midTermTheory || '' }}</span>
						</template>
					</el-table-column>

					<!-- 期末列 -->
					<el-table-column label="期末" width="85" align="center">
						<template #default="{ row }">
							<el-input
								v-if="isEditing"
								v-model="row.scores.finalTheory"
								@change="(value: string) => updateScore(row, 'finalTheory', value)"
								:class="{ 'invalid-input': invalidScores[`${row.userId}_finalTheory`] }"
							/>
							<span v-else>{{ row.scores.finalTheory || '' }}</span>
						</template>
					</el-table-column>

					<!-- 平时列 -->
					<el-table-column label="平时" width="85" align="center">
						<template #default="{ row }">
							<el-input
								v-if="isEditing"
								v-model="row.scores.usualTheory"
								@change="(value: string) => updateScore(row, 'usualTheory', value)"
								:class="{ 'invalid-input': invalidScores[`${row.userId}_usualTheory`] }"
							/>
							<span v-else>{{ row.scores.usualTheory || '' }}</span>
						</template>
					</el-table-column>

					<!-- 总分列 -->
					<el-table-column label="总分" label-color="#2676ee" width="80" align="center">
						<template #default="{ row }">
							<span class="total-score">{{ calculateTotal(row.scores, 'theory') }}</span>
						</template>
					</el-table-column>
				</el-table-column>

				<!-- 实践成绩部分 -->
				<el-table-column label="实践成绩" align="center">
					<!-- 考试情况选择 -->
					<el-table-column label="考试情况" width="100" align="center">
						<template #default="{ row }">
							<el-select
								v-if="isEditing"
								v-model="row.scores.aboutPractice"
								placeholder="选择"
								@change="(value: ExamStatus) => updateScore(row, 'aboutPractice', value)"
							>
								<el-option
									v-for="item in examStatusOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</el-select>
							<span v-else>{{
								examStatusOptions.find((o) => o.value === row.scores.aboutPractice)?.label
							}}</span>
						</template>
					</el-table-column>

					<!-- 期中列 - 只在普通科目时显示 -->
					<el-table-column
						v-if="filterForm.subjectType === 'normal'"
						label="期中"
						width="85"
						align="center"
					>
						<template #default="{ row }">
							<el-input
								v-if="isEditing"
								v-model="row.scores.midTermPractice"
								@change="(value: string) => updateScore(row, 'midTermPractice', value)"
								:class="{ 'invalid-input': invalidScores[`${row.userId}_midTermPractice`] }"
							/>
							<span v-else>{{ row.scores.midTermPractice || '' }}</span>
						</template>
					</el-table-column>

					<!-- 期末列 -->
					<el-table-column label="期末" width="85" align="center">
						<template #default="{ row }">
							<el-input
								v-if="isEditing"
								v-model="row.scores.finalPractice"
								@change="(value: string) => updateScore(row, 'finalPractice', value)"
								:class="{ 'invalid-input': invalidScores[`${row.userId}_finalPractice`] }"
							/>
							<span v-else>{{ row.scores.finalPractice || '' }}</span>
						</template>
					</el-table-column>

					<!-- 平时列 -->
					<el-table-column label="平时" width="85" align="center">
						<template #default="{ row }">
							<el-input
								v-if="isEditing"
								v-model="row.scores.usualPractice"
								@change="(value: string) => updateScore(row, 'usualPractice', value)"
								:class="{ 'invalid-input': invalidScores[`${row.userId}_usualPractice`] }"
							/>
							<span v-else>{{ row.scores.usualPractice || '' }}</span>
						</template>
					</el-table-column>

					<!-- 总分列 -->
					<el-table-column label="总分" label-color="#2676ee" width="80" align="center">
						<template #default="{ row }">
							{{ calculateTotal(row.scores, 'practice') }}
						</template>
					</el-table-column>
				</el-table-column>
			</el-table>
		</el-card>
	</div>
</template>

<style lang="scss" scoped>
.score-input {
	padding: 20px;

	.filter-card {
		margin-bottom: 20px;

		.filter-form {
			.form-row {
				position: relative;
				display: flex;
				flex-wrap: wrap;
				gap: 20px;
				align-items: flex-start;

				:deep(.el-form-item) {
					margin-bottom: 0;

					.el-select {
						width: 340px;
					}
				}
			}

			.small-item {
				width: 180px;
			}
		}
	}

	.table-card {
		.table-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;

			.title-section {
				h3 {
					margin: 0;
					font-size: 16px;
					margin-bottom: 8px;
				}
			}

			.selected-info {
				font-size: 13px;
				color: #666;
				display: flex;
				gap: 15px;

				span {
					white-space: nowrap;
				}
			}

			.button-group {
				display: flex;
				gap: 10px;
				align-items: center;
			}
		}

		.score-table {
			:deep(.el-table__header) {
				th {
					background-color: #f5f7fa;
					padding: 8px 0;
				}
			}

			// 添加无效输入的样式
			:deep(.invalid-input) {
				color: #dd0606;

				.el-input__inner {
					color: #dd0606;
					font-weight: bold;
				}
			}
		}
	}
}

.total-score {
	color: #2676ee;
	font-weight: bold;
}

:deep(.total-score-label) {
	color: #2676ee !important;
	font-weight: bold;
}

.filter-form {
	.form-row {
		.small-item {
			:deep(.el-select) {
				width: 280px !important; // 调整选择框宽度以适应更长的文本
			}
		}
	}
}
</style>
